package andromeda.httpCommunication;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.*;
import org.apache.http.client.methods.*;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieSpecRegistry;
import org.apache.http.impl.client.*;
import org.apache.http.message.*;
import org.apache.http.params.*;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.beans.FilterBean;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.HasChildFilter;
import org.htmlparser.filters.HasParentFilter;
import org.htmlparser.filters.StringFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.FormTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import android.R.string;
import android.util.Log;


public class Test {
	public Test(){
		
	}
	
	private String inputStreamToString(InputStream is) throws IOException {
	    String line = "";
	    StringBuilder total = new StringBuilder();
	    
	    // Wrap a BufferedReader around the InputStream
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

	    // Read response until the end
	    while ((line = rd.readLine()) != null) { 
	        total.append(line); 
	    }
	    
	    // Return full string
	    return total.toString();
	}
	
	/*
	 * // Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost("http://rsickinger.dyndns.org/authtest/login.php");

	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("username", "12345"));
	        nameValuePairs.add(new BasicNameValuePair("password", "hoot"));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        
	        
	        
	        return inputStreamToString(response.getEntity().getContent());
	        
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	    
		return null;
	 * */
	
	//funktioniert nun auch auf eama!!!!!
	
	protected NodeList getNodes (Parser mParser, NodeFilter[] filters)
	        throws
	            ParserException
	    {
	        NodeList ret;

	        ret = mParser.parse (null);
	        
	        if (null != filters)
	            for (int i = 0; i < filters.length; i++)
	                ret = ret.extractAllNodesThatMatch (filters[i], true);

	        return (ret);
	    }
	
	public String Login() throws ParserException, ClientProtocolException, IOException{
		return postData();
	}
	
	public String getPostUrl(){
		return "";
	}
	
	public NodeList FilterData(String s) throws ParserException{
		
		Parser p = new Parser();
		
		p.setInputHTML(s);
		
		StringFilter filter0 = new StringFilter ();
        filter0.setCaseSensitive (false);
        filter0.setLocale (new java.util.Locale ("de", "DE", ""));
        filter0.setPattern ("om nummer");
        HasChildFilter filter1 = new HasChildFilter ();
        filter1.setRecursive (true);
        filter1.setChildFilter (filter0);
        TagNameFilter filter2 = new TagNameFilter ();
        filter2.setName ("TABLE");
        TagNameFilter filter3 = new TagNameFilter ();
        filter3.setName ("P");
        HasParentFilter filter4 = new HasParentFilter ();
        filter4.setRecursive (false);
        filter4.setParentFilter (filter3);
        NodeFilter[] array0 = new NodeFilter[3];
        array0[0] = filter1;
        array0[1] = filter2;
        array0[2] = filter4;
        AndFilter filter5 = new AndFilter ();
        filter5.setPredicates (array0);
        NodeFilter[] array1 = new NodeFilter[1];
        array1[0] = filter5;
        
        
        return p.parse(filter5);
	}
	
	public String postData() throws ParserException, ClientProtocolException, IOException {
		
		String erg = "";
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		
		//httpclient.set;
		Parser p = new Parser();
		
        try {
            HttpGet httpget = new HttpGet("https://services.ama.at/servlet/");

            HttpResponse response;
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            erg += "Login form get: " + response.getStatusLine() + "\n";
            String homeP = inputStreamToString(response.getEntity().getContent());
            //EntityUtils

            //System.out.println("Initial set of cookies:");
            //List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            /*if (cookies.isEmpty()) {
            	erg += "None" + "\n";
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                	erg += "- " + cookies.get(i).toString() + "\n";
                }
            }*/
            
            /*TagNameFilter filter0 = new TagNameFilter ();
	        filter0.setName ("FORM");
	        HasAttributeFilter filter1 = new HasAttributeFilter ();
	        filter1.setAttributeName ("name");
	        filter1.setAttributeValue ("LOGIN");
	        NodeFilter[] array0 = new NodeFilter[2];
	        array0[0] = filter0;
	        array0[1] = filter1;
	        AndFilter filter2 = new AndFilter ();
	        filter2.setPredicates (array0);
	        NodeFilter[] array1 = new NodeFilter[1];
	        array1[0] = filter2;

	        
	        p.setInputHTML(homeP);
	        
	        NodeList l = p.parse(filter2);
	       
	        Node[] li = l.toNodeArray();
	       
	        FormTag t = (FormTag) li[0];
		
	       
	       
			String actionpost = t.getAttribute("action");*/
            

            //HttpPost httpost = new HttpPost("https://services.ama.at/servlet/" + actionpost);
			HttpPost httpost = new HttpPost("https://services.ama.at/servlet/?wicket:bookmarkablePage=:at.ama.eama.ui.portal.StartPage&wicket:interface=:1:pagecenter:header:loginPanel:login:loginForm:3:IFormSubmitListener::");
			
            List <NameValuePair> params = new ArrayList <NameValuePair>();
            params.add(new BasicNameValuePair("id3_hf_0", ""));
            params.add(new BasicNameValuePair("pinNumber", "2265729"));
	        params.add(new BasicNameValuePair("pinCode", "mobilkom007"));
	        params.add(new BasicNameValuePair("OS", "Linux i686"));
	        params.add(new BasicNameValuePair("BNAME", "Netscape"));
	        params.add(new BasicNameValuePair("BVERS", "BVERS=5.0 (X11)"));
	        params.add(new BasicNameValuePair("UA", "UA=Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0"));
	        params.add(new BasicNameValuePair("SCREEN", "1600;848;1600;739;1585;1341"));
	        params.add(new BasicNameValuePair("SCREEN_DIMENSIONS", "1600/900"));
	        params.add(new BasicNameValuePair("WINDOW_DIMENSIONS", "1600/713"));

            httpost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            response = httpclient.execute(httpost);
            //entity = response.getEntity();
            String homeP2 = inputStreamToString(response.getEntity().getContent());

            //erg += homeP2;
            
            if(homeP2.toLowerCase().contains("fehl"))
            	erg += "JUHUUuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuUUU CONTING FEHLER";
            
           boolean logon = false;
            if(homeP2.toLowerCase().contains("utzungsprotokoll")){
        	   erg += "DRIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIINENENENENEN";
        	   logon = true;
            }
            	
            erg += "Login form get: " + response.getStatusLine();
            //EntityUtils.consume(entity);

            erg += "Post logon cookies:------------------------------------------------------";
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            String sessid = "";
            if (cookies.isEmpty()) {
            	erg += "None";
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                	erg += "- " + cookies.get(i).toString();
                	if(cookies.get(i).getName().toLowerCase().equals("jsessionid"))
                		sessid = cookies.get(i).getValue();
                }
            }
            
            if(logon){
            	erg += ">>>>" + sessid;
            	httpost = new HttpPost("https://services.ama.at/servlet/eama?sessionID=" + sessid + "&query=?rn.post.stallregister.c0.DATVON.DATBIS");
            	
            	params = new ArrayList <NameValuePair>();
            	Date t = new Date();
            	
            	SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
            	
                params.add(new BasicNameValuePair("DATVON", format.format(t)));
                params.add(new BasicNameValuePair("DATBIS", format.format(t)));
                
                httpost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                response = httpclient.execute(httpost);
                //entity = response.getEntity();
                String homeP3 = inputStreamToString(response.getEntity().getContent());
            	
                //erg += homeP3;
                
                NodeList l = FilterData(homeP3);
                
                TableTag table = (TableTag) l.elementAt(0);
                
                for(int i = 1; i < table.getRowCount(); i++){
                	TableRow tr = table.getRow(i);
                	
                	//         td            a     
                	erg += tr.getChild(0).getFirstChild().getFirstChild().getText();
                	
                	
                }
            }
            
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
		
		return erg;
	}
}
